package servlet;

import com.baidu.ai.aip.utils.GetName;
import com.com.baidu.ai.aip.AI;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@WebServlet(urlPatterns = "/ai")
public class AiServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String m = req.getParameter("m");
        if ("del".equals(m)){
            //清楚session
            delS(req,resp);
        }else {
            see(req,resp);
        }

    }

    private void delS(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //delete session
        req.getSession().invalidate();
        // 跳转页面
        resp.sendRedirect("index.jsp");
    }

    private void see(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取文件地址
        String fileURL = (String) req.getSession().getAttribute("fileURL");
        System.out.println("AI层获取的fileURL：" + fileURL);
        resp.setContentType("text/html;charset=utf-8");
        //判断是否存在返回信息
        PrintWriter writer = resp.getWriter();
        if (fileURL == null || Objects.equals(fileURL, "")) {
            writer.println("<script>location.href='index.jsp';alert('文件不可以为空奥，乖乖！');</script>");
        } else {

            String url = "../../artifacts/WEB_war_exploded/"+fileURL;
            String thing = req.getParameter("thing");
            //调取AI获取API回馈的信息，判断Ai类型
            if ("animal".equals(thing)){//动物AI
                String result=AI.animal(url);
                ct(req,resp,result);
            }else if ("plant".equals(thing)){//植物AI
                String result = AI.plant(url);
                //对回馈信息进行有效信息提取
                ct(req,resp,result);
            }else {
                //敬请期待更多功能
                writer.println("<script>location.href='success.jsp';alert('亲爱的该功能，己墨正在玩命开发中！敬请期待。');</script>");
            }
        }
    }

    /***
     * 默认的提取数据
     * @param req
     * @param resp
     * @param result
     * @throws ServletException
     * @throws IOException
     */
    public static void ct(HttpServletRequest req, HttpServletResponse resp,String result) throws ServletException, IOException {
        //对回馈信息进行有效信息提取
        String name =(String)GetName.JJ(result,GetName.ZERO,GetName.NAME);
        String score =(String) GetName.JJ(result,GetName.ZERO,GetName.SCORE);
        req.getSession().setAttribute("name1",name);
        req.getSession().setAttribute("score1",score);
        //存入信息，跳转页面}
        req.getRequestDispatcher("ai.jsp").forward(req,resp);
    }
}
